﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
//方法一
using System.Runtime;
using System.Runtime.InteropServices;
//方法二 Net2.0新增类库
using System.Net.NetworkInformation;

namespace Tools.Framework
{
    public class InternetHelper
    {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);

        #region 方法一
        /// <summary>
        /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败 
        /// </summary>
        /// <returns></returns>
        public static bool IsConnectInternet()
        {
            int Description = 0;
            return InternetGetConnectedState(Description, 0);
        }
        #endregion

        #region 方法二
        /// <summary>
        /// 用于检查IP地址或域名是否可以使用TCP/IP协议访问(使用Ping命令),true表示Ping成功,false表示Ping失败 
        /// </summary>
        /// <param name="strIpOrDName">输入参数,表示IP地址或域名</param>
        /// <returns></returns>
        public static bool PingIpOrDomainName(string strIpOrDName)
        {
            try
            {
                Ping ping = new Ping();
                PingReply pingReply = ping.Send(strIpOrDName);
                if (pingReply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    return false;
                }  
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion

        /// <summary>
        /// 获取url 网络访问状态（是否正常访问）
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool GetHttpState(string url)
        {
            try
            {
                HttpWebRequest myReq = (HttpWebRequest) WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse) myReq.GetResponse();
                return response.StatusCode == HttpStatusCode.OK;
            }
            catch (Exception)
            {
                return false;
            }
        }

       
    }
}

